from quadTree import QuadTree
from eventServer import eventServer

class CollisionServer():
    
    def __init__(self):
        self.tree = QuadTree()
        self.cObjects = []
        
        eventServer.registerToBack("update",self.pull)
        
    def initialize(self, mapWidth, centerX, centerY):
        self.tree.resize(mapWidth, centerX, centerY, 2)
        
    def clear(self):
        self.tree.clear()
        self.cObjects = []
        
    def register(self, geometry):
        self.cObjects.append(geometry)
        self.tree.insert(geometry)
        
    def unregister(self, geometry):
        if(geometry in self.cObjects):
            self.cObjects.remove(geometry)
        self.tree.remove(geometry)
        
    def pull(self, cmd, args):
        for c in self.cObjects:
            c.setVar("collisions", [])
            active = c.getVar("cActive")
            if(active):
                self.tree.remove(c)
            else:
                if(c.updateCollisionInformation()):
                    self.tree.remove(c)
                    self.tree.insert(c)
        
        for c in self.cObjects:
            active = c.getVar("cActive")
            if(active):
                c.updateCollisionInformation()
                self.tree.detectCollisions(c)
                self.tree.insert(c)
            
collisionServer = CollisionServer()